import {compose, withState} from 'recompose'
import {Button} from 'antd'

const CutDown = ({seconds, setState, state, onClick}) => (
    <Button type="primary" ghost
            onClick={() => click({seconds: seconds || 0, setState, state, onClick})}
            disabled={state.seconds > 0}>
        {state.seconds > 0 ? state.seconds + '秒后再试' : '发送验证码'}
    </Button>
)

export default compose(
    withState('state', 'setState', ({seconds}) => ({
        seconds: -1
    }))
)(CutDown)


const click = (values: { seconds: number, setState: Function, state: { seconds: number }, onClick: Function }) => {
    let s = values.seconds || 0;
    if (values.state.seconds > 0) return
    const ret = values.onClick();
    if(ret) return
    const timer = setInterval(() => {
        s--;
        values.setState({seconds: s})
        if (s > 0) {
            values.setState({seconds: s})
        } else {
            values.setState({seconds: -1})
            clearInterval(timer);
        }
    }, 800)
}